package com.yeziji.config.support.redis;

import com.yeziji.utils.expansion.Lists2;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Redis 过期监听器
 *
 * @author hwy
 * @since 2024/11/29 10:34
 **/
@Component
public class RedisExpiredListener implements MessageListener, InitializingBean {
    Map<String, RedisExpiredHandler> redisExpiredHandlerMap = new HashMap<>();
    @Autowired(required = false)
    private List<RedisExpiredHandler> expiredHandlerList;

    @Override
    public void onMessage(Message message, @Nullable byte[] pattern) {
        for (Map.Entry<String, RedisExpiredHandler> redisExpiredEventEntry : redisExpiredHandlerMap.entrySet()) {
            String expiredKey = message.toString();
            Pattern realPattern = Pattern.compile(redisExpiredEventEntry.getKey());
            // 通过正则比对处理器的 key 与过期 key 的区别
            Matcher matcher = realPattern.matcher(expiredKey);
            if (matcher.matches()) {
                redisExpiredEventEntry.getValue().handler(expiredKey);
                break; // find one break
            }
        }
    }

    @Override
    public void afterPropertiesSet() {
        if (Lists2.isNotEmpty(expiredHandlerList)) {
            expiredHandlerList.forEach(handler -> redisExpiredHandlerMap.put(handler.getKey(), handler));
        }
    }
}
